<template>
	<div>
		<BreadCrumb pathOne="内容管理" pathTwo="文章管理" ></BreadCrumb>
		<div>
			<el-form :inline="true">
				<el-form-item label="文章名" size="large">
					<el-input clearable size="large" v-model="searchName" style="width: 240px" placeholder="请输入文章名" />
				</el-form-item>
				<el-form-item label="咨询师作者" size="large">
					<el-select @clear="counselorId=''" clearable v-model="counselorId" placeholder="无" size="large"
						style="width: 240px">
						<el-option v-for="item in AllAuthor" :key="item.id" :value="item.id" :label="item.counselorName" />
					</el-select>
				</el-form-item>
				<el-form-item label="选择分类" size="large">
					<el-select @clear="articleClassifyId=''" clearable v-model="articleClassifyId" placeholder="无"
						size="large" style="width: 240px">
						<el-option v-for="item in AllClassify" :key="item.id" :value="item.id"
							:label="item.articleClassifyName" />
					</el-select>
				</el-form-item>
				<el-form-item>
					<el-button type="primary" @click="query" size="large">搜索</el-button>
					<el-button type="primary" @click="createOrUpdate('')" size="large">新增</el-button>
					<el-button type="danger" size="large" @click="batchDelete">批量删除</el-button>
				</el-form-item>
			</el-form>

		</div>
		<div>
			<el-table :data="tableData" style="width: 100%;margin-top: 10px;" border
				:header-cell-style="{textAlign: 'center'}" :cell-style="{ textAlign: 'center' }" @selection-change="handleSelectionChange">
				<el-table-column type="selection" width="40" />
				<el-table-column fixed prop="id" label="id"/>
				<el-table-column prop="name" label="文章名"  show-overflow-tooltip />
				<el-table-column prop="description" label="文章简介"  show-overflow-tooltip />
				<el-table-column prop="counselor.name" label="咨询师名"  />
				<el-table-column label="缩略图" >
					<template #default="scope">
						<!-- <img :src="scope.row.counselor.counselorImg" alt="缩略图"> -->
						<el-avatar shape="square" size="large" :src="'http://localhost:8080' + scope.row.listView" />
					</template>
				</el-table-column>

				<el-table-column prop="personCount" label="阅读量"  />
				<el-table-column prop="articalClassification.name" label="所属分类"  />
				<el-table-column prop="time" label="创建时间" width="180" />
				<el-table-column label="审核状态" width="110">
					<!-- 0是审核中，1是通过，2是不通过 -->
					<template #default="scope">
						<el-tag type="warning" v-if="scope.row.status==0">审核中</el-tag>
						<el-tag type="success" v-else-if="scope.row.status==1">已审核</el-tag>
						<el-tag type="danger" v-else>审核未通过</el-tag>
					</template>
				</el-table-column>
				<el-table-column label="状态" width="70">
					<!-- 0是审核中，1是通过，2是不通过 -->
						<el-tag type="success">正常</el-tag>
				</el-table-column>
				<el-table-column fixed="right" label="操作" width="260">
					<template #default="scope">
						<el-button size="small" type="primary" @click="createOrUpdate(scope.row.id)">编辑</el-button>
						<el-button size="small" type="danger" @click="remove(scope.row.id)">删除</el-button>
						<el-button size="small" type="primary" @click="searchArticleDetails(scope.row.id)">查看详情内容</el-button>
					</template>
				</el-table-column>
			</el-table>
		</div>
		<el-pagination v-model:current-page="currentPage" v-model:page-size="pageSize" :page-sizes="[5, 10,15, 20]"
			:size="size" layout="total, sizes, prev, pager, next, jumper" :total="total" @size-change="handleSizeChange"
			@current-change="handleCurrentChange" />
		<el-dialog v-model="dialogFormVisible" :title="form.id==''?'新增':'编辑'" width="700" style="margin-bottom: 60px;"
			@close="handleClose">
			<!-- <el-form :model="form"> -->
			<el-form>
				<el-form-item label="文章标题" label-width="auto" label-position='top'>
					<el-input size="large" v-model="form.name" autocomplete="off"
						placeholder="请输入文章标题" />
				</el-form-item>
				<el-form-item label="文章简介" label-width="auto" label-position='top'>
					<el-input size="large" v-model="form.description" autocomplete="off"
						placeholder="请输入文章简介" />
				</el-form-item>
				<el-form-item label="咨询师作者" size="large" label-position='top'>
					<el-select v-model="form.psycCounselorId" placeholder="无" size="large">
						<el-option v-for="item in AllAuthor" :key="item.id" :value="item.id" :label="item.counselorName" />
					</el-select>
				</el-form-item>
				<el-form-item label="缩略图" label-position='top'>
					<el-upload class="avatar-uploader"
						action="http://localhost:8080/upload" :show-file-list="false"
						:on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">
						<img
              v-if="form.listView"
              :src="'http://localhost:8080' + form.listView"
              class="avatar"
            />
						<el-icon v-else class="avatar-uploader-icon">
							<Plus />
						</el-icon>
					</el-upload>
				</el-form-item>
				<el-form-item label="文章内容详情" label-width="auto" label-position='top'>
					<!-- <el-input size="large" v-model="form.articleDetails" autocomplete="off"
						placeholder="请输入文章内容详情" /> -->
						<QuillEditor :value="form.detail" @updateValue="getMsg"></QuillEditor>
						<!-- <QuillEditor :value="emailForm.msg" @updateValue="getMsg"></QuillEditor> -->
				</el-form-item>
				<el-form-item label="所属分类" size="large" label-position='top'>
					<el-select v-model="form.classificationId" placeholder="无" size="large">
						<el-option v-for="item in AllClassify" :key="item.id" :value="item.id" :label="item.articleClassifyName" />
					</el-select>
				</el-form-item>
				<!-- 0是审核中，1是通过，2是不通过 -->
				<el-form-item label="审核状态" size="large" label-position='top'>
					<el-select v-model="form.status" placeholder="无" size="large">
						<el-option :value="0" label="审核中" />
						<el-option :value="1" label="通过" />
						<el-option :value="2" label="不通过" />
					</el-select>
				</el-form-item>
			</el-form>
			<template #footer>
				<div class="dialog-footer">
					<el-button @click="dialogFormVisible = false">取消</el-button>
					<el-button type="primary" @click="dialogFormVisible = false,add()">
						确定
					</el-button>
				</div>
			</template>
		</el-dialog>
		<el-dialog v-model="dialogArticleDetails" title="内容详情" width="700" style="margin-bottom: 60px;"
			@close="handleClose">
			<el-form-item label="" label-width="auto" label-position='top'>
					<QuillEditor :value="form.detail" @updateValue="getMsg"></QuillEditor>
			</el-form-item>
			<el-form-item label="" label-width="auto" >
					<el-button size="large" type="primary" @click="handleClose" style="position:absolute;right: 0px;margin: 10px 0;">关闭</el-button>
			</el-form-item>
			</el-dialog>
	</div>
</template>

<script setup>
	import {
		getCurrentInstance,
		onMounted,
		reactive,
		ref
	} from 'vue'
	import {
		ElMessage,
		ElMessageBox
	} from 'element-plus'
	import { Plus } from '@element-plus/icons-vue'
	import BreadCrumb from "../../components/BreadCrumb.vue"
	import QuillEditor from "../../components/QuillEditor.vue"
	const getMsg = (val) => {
		// console.log('form.value.articleDetails',form.value.articleDetails);
	form.value.articleDetails = val
	}
	const AllAuthor = ref([])
	const AllClassify = ref([])
	const axios = getCurrentInstance().appContext.config.globalProperties.axios;
	const getAllAuthor = () => {
		axios.get(
			'http://localhost:8080/counselor/id/all',
		).then(resp => {
			console.log('全部作者：', resp);
			AllAuthor.value = resp.data
		})
	}
	const getAllClassify = () => {
		axios.get(
			'http://localhost:8080/articalClassification/all',
		).then(resp => {
			console.log('全部分类：', resp);
			AllClassify.value = resp.data
			console.log('全部分类',AllClassify.value)
		})
	}
	const tableData = ref([])
	
	const counselorId = ref('')
	const articleClassifyId = ref('')
	const query = () => {
		const params = {
    pageNum: currentPage.value,
    pageSize: pageSize.value,
  }
	if (searchName.value !== '') {
    // 判断不为空字符串
    params.name = searchName.value
  }
	if (counselorId.value !== '') {
    // 判断不为空字符串
    params.psycCounselorId = counselorId.value
  }
  if (articleClassifyId.value !== '') {
    // 判断不为空字符串
    params.classificationId = articleClassifyId.value
  }
	
		axios.get(
			'http://localhost:8080/artical/page',
			{
				params:params
			}
		).then(resp => {
			console.log('数据查询请求：', resp);
			tableData.value = resp.data.pageInfo.list
			total.value = resp.data.pageInfo.total
			console.log("表格数据：", tableData.value);
		})
	}
	const currentPage = ref(1) // 当前页
	const pageSize = ref(10) // 每页显示条目数
	const size = 'default' // 分页大小
	const total = ref(0)
	const handleSizeChange = (val) => {
		pageSize.value = val;
		query();
	}
	const handleCurrentChange = (val) => {
		currentPage.value = val
		query();
	}
	const searchName = ref('')
	const dialogFormVisible = ref(false)
	const dialogArticleDetails=ref(false)
	// const articleClassifyName = ref('')
	const handleClose = () => {
		form.value ={
			addOrUpdateFlag: 1,
			articalClassification: {
				name: "",
				del: 0,
				id: ""
			},
			classificationId: '',//分类
			time: "",
			detail: ' ',//<p>新增文章内容详情</p>
			id: "",
			description: "",//新增简介
			name: "",//新增文章
			listView: "",
			counselor: {
				name: ""
			},
			psycCounselorId: '',//咨询作者
			del: '0',
			personCount: "",
			status: "",//0是审核中，1是通过，2是不通过
		}
	}
	const createOrUpdate = (id) => {
		console.log("id为",id);
		dialogFormVisible.value = true
		if (id == '') {
			handleClose();
			
		} else {
			axios.get(
				'http://localhost:8080/artical',{
					params:{
						id:id
					}
				}
			).then(resp => {
				form.value = resp.data
				// emailForm.value.msg=form.value.articleDetails
				console.log('编辑查询：', resp);
			})
		}
	}
	const searchArticleDetails=(id)=>{
		dialogArticleDetails.value = true
		if (id == '') {
			handleClose();
		
		} else {
			axios.get(
				'http://localhost:8080/artical',{
					params:{
						id:id
					}
				},
			).then(resp => {
				form.value = resp.data
				console.log('编辑查询：', resp);
			})
		}
	}
	const form = ref({
			addOrUpdateFlag: 1,
			articalClassification: {
				name: "",
				del: 0,
				id: ""
			},
			classificationId: '',//分类
			time: "",
			detail: ' ',//<p>新增文章内容详情</p>
			id: "",
			description: "",//新增简介
			name: "",//新增文章
			listView: "",
			counselor: {
				name: ""
			},
			psycCounselorId: '',//咨询作者
			del: '0',
			personCount: "",
			status: "",//0是审核中，1是通过，2是不通过
		})
	const add = () => {
			console.log('点击新增保存后传入的：', form.value);
		if (form.value.id == '') {
			form.value.time = getCurrentFormattedDateTime()
			axios.post('http://localhost:8080/artical/add-selective', form.value).then(resp => {
				if (resp.code == 200) {
					ElMessage({
						message: '新增成功',
						type: 'success',
					})
				} else {
					ElMessage.error('新增失败')
				}
			}).finally(() => {
				query();
			})
		} else {
			axios.put('http://localhost:8080/artical', form.value).then(resp => {
				if (resp.code == 200) {
					ElMessage({
						message: '修改成功',
						type: 'success',
					})
				} else {
					ElMessage.error('修改失败')
				}
			}).finally(() => {
				query();
			})
		}
	}
	const remove = (id) => {
		console.log('当前行的数据', id);
		ElMessageBox.confirm(
				'此操作将永久删除该文件, 是否继续?',
				'提示', {
					confirmButtonText: '确认',
					cancelButtonText: '取消',
					type: 'warning',
				}
			)
			.then(() => {
				axios.delete('http://localhost:8080/artical',{
					params:{
						id:id
					}
				}

				).then((resp) => {
					console.log('删除后：', resp);
					if (resp.code == 200) {
						ElMessage({
							message: '删除成功',
							type: 'success',
						})
					} else {
						ElMessage.error('删除失败')
					}
				}).finally(() => {
					query();
				});

			})
			.catch(() => {
				ElMessage({
					type: 'info',
					message: '取消删除',
				})
			})

	}
	const ids = ref('')
	const handleSelectionChange = (selection) => {
		ids.value = selection.map(item => item.id).join(',')
		console.log('批量删除的ids为:', ids.value)
	}
	
	const batchDelete = () => {
		if (!ids.value) {
			ElMessage.info('请选择要删除的数据')
			return
		}
		ElMessageBox.confirm('此操作将永久删除该文件, 是否继续?', '提示', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'warning'
		}).then(() => {
			axios.delete('http://localhost:8080/artical/batch',{
				params:{
					ids:ids.value
				}
			}).then(res => {
				ElMessage.success('删除成功')
				query();
			})
		}).catch(() => {
			ElMessage.info('已取消删除')
		}).finally(() => {
			query();
		});
	}
function handleAvatarSuccess(resp) {
  console.log('文件上传成功', resp)
  form.value.listView = resp.data
}

function getCurrentFormattedDateTime() {
  const now = new Date() // 获取当前的 Date 对象

  // 提取日期部分
  const year = now.getFullYear()
  // getMonth() 返回 0-11，所以需要 +1
  // padStart(2, '0') 确保是两位数，不足补零
  const month = (now.getMonth() + 1).toString().padStart(2, '0')
  const day = now.getDate().toString().padStart(2, '0')

  // 提取时间部分
  const hours = now.getHours().toString().padStart(2, '0')
  const minutes = now.getMinutes().toString().padStart(2, '0')
  const seconds = now.getSeconds().toString().padStart(2, '0')

  // 拼接成目标格式的字符串
  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}
	onMounted(() => {
		query()
		getAllAuthor()
		getAllClassify()
	})
</script>

<style scoped>
	.avatar-uploader .avatar {
	  width: 178px;
	  height: 178px;
	  display: block;
	}
	.avatar-uploader .el-upload {
		border: 1px dashed var(--el-border-color);
		border-radius: 6px;
		cursor: pointer;
		position: relative;
		overflow: hidden;
		transition: var(--el-transition-duration-fast);
	}
	
	.avatar-uploader .el-upload:hover {
		border-color: var(--el-color-primary);
	}
	
	.el-icon.avatar-uploader-icon {
		font-size: 28px;
		color: #8c939d;
		width: 178px;
		height: 178px;
		text-align: center;
	}
</style>